﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OracleClient;
using System.Data;

/*
 * Author:Conis
 * Date:
 * Description:SQL语句中的比较单元
 */

namespace Conis.Squirrel.SqlBuilder.Oracle
{
    /// <summary>
    /// SQL语句的比较单元
    /// </summary>
    public class CompareUnit<T> : BaseCompareUnit<T>
    {
        protected internal CompareUnit(Connector connector, string fieldName, CompareOperator compare, T value, bool valueIsSafe) :
            base(connector, fieldName, compare, value, valueIsSafe) { }

        /// <summary>
        /// 创建一个参数
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        protected override IDataParameter CreateParameter(string key, object value)
        {
            return new OracleParameter(key, value);
        }

        /// <summary>
        /// 循环之前的
        /// </summary>
        protected override void LoopBefore()
        {
            string value = this.Value.ToString();
            if (!this.ValueIsSafe)
            {
                string paramValue;
                value = "G";
                value += Guid.NewGuid().ToString("N");
                value = value.Substring(0, 25);
                //检查是事为Like
                switch (this.Compare)
                {
                    case CompareOperator.Like:
                        paramValue = string.Format("%{0}%", this.Value);
                        break;
                    case CompareOperator.StartLike:
                        paramValue = string.Format("%{0}", this.Value);
                        break;
                    case CompareOperator.EndLike:
                        paramValue = string.Format("{0}%", this.Value);
                        break;
                    default:
                        paramValue = this.Value.ToString();
                        break;
                }
                this.paramsList.Add(this.CreateParameter(value, paramValue));
            }

            //除了第一个条件，其它的条件需要加上连接符
            if (this.currentIndex != 0)
            {
                this.container.Append(this.Connector.ToSql());
            }
            this.container.Append(this.FieldName).Append(this.Compare.ToSql()).Append(":").Append(value);
        }
    }
}
